package cc.magicjson.openapi.interfaces.rest;


import cc.magicjson.openapi.domain.model.User;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private List<User> users = new ArrayList<>();

    /**
     * get all users
     * 
     * @return get all users
     */
    @GetMapping
    public List<User> getAllUsers() {
        return users;
    }

    /**
     * get user by id
     * 
     * @param id userid
     * @return user object if found, null if not found
     */
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return users.stream()
                .filter(user -> user.getId().equals(id))
                .findFirst()
                .orElse(null);
    }

    /**
     * 创建新用户
     * 
     * @param user 用户对象
     * @return 创建的用户对象
     */
    @PostMapping
    public User createUser(@RequestBody User user) {
        user.setId((long) (users.size() + 1));
        users.add(user);
        return user;
    }

    /**
     * 更新用户信息
     * 
     * @param id 用户ID
     * @param user 更新的用户信息
     * @return 更新后的用户对象，如果用户不存在返回null
     */
    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User user) {
        for (int i = 0; i < users.size(); i++) {
            if (users.get(i).getId().equals(id)) {
                user.setId(id);
                users.set(i, user);
                return user;
            }
        }
        return null;
    }

    /**
     * 删除用户
     * 
     * @param id 用户ID
     * @return 删除成功返回true，否则返回false
     */
    @DeleteMapping("/{id}")
    public boolean deleteUser(@PathVariable Long id) {
        return users.removeIf(user -> user.getId().equals(id));
    }
}